﻿using BaGet.Protocol.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace Niaofei.Nuget
{
    public class NugetWindowViewModel : ObservableObject
    {
        private string searchText = "";
        private readonly NiaofeiNuGetClient _client;
        private bool _isPreview;
        private SearchResult? _nuget;
        private ObservableCollection<string> _searchTexts = [];
        private ObservableCollection<SearchResult> _nugets = [];

        public NugetWindowViewModel()
        {
            _client = new NiaofeiNuGetClient("https://api.nuget.org/v3/index.json");

            SearchCommand = new AsyncRelayCommand(Search);
            DownloadCommand = new RelayCommand(Download);
        }

        public ICommand SearchCommand { get; set; }
        public ICommand DownloadCommand { get; set; }

        public string SearchText
        {
            get => searchText;
            set
            {
                searchText = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<string> SearchTexts
        {
            get => _searchTexts;
            set
            {
                _searchTexts = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<SearchResult> Nugets
        {
            get => _nugets;
            set
            {
                _nugets = value;
                OnPropertyChanged();
            }
        }

        public SearchResult? Nuget
        {
            get => _nuget;
            set
            {
                _nuget = value;
                OnPropertyChanged();
            }
        }


        public bool IsPreview
        {
            get => _isPreview;
            set
            {
                _isPreview = value;
                OnPropertyChanged();
            }
        }


        private async Task Search()
        {
            var nugets = await _client.SearchClient.SearchAsync(searchText);

            Nugets.Clear();
            Nugets.AddRange(nugets.Data);
        }

        private void Download()
        {
            if (Nuget != null)
            {
                var vm = new DownloadWindowViewModel(Nuget);
                var win = new DownloadWindow()
                {
                    DataContext = vm,
                };

                win.ShowDialog();
            }
        }
    }
}
